import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import os
import sys
import cv2
import numpy as np
from scipy import ndimage, stats
import threading
import glob2 as glob

root = tk.Tk()
root.geometry("500x500")
root.title("照片质量检测工具（手动版）v24.1")

default_encoding = sys.getfilesystemencoding()

folder_selected = None
my_files = None


def main_quality_check(img_name):
    # im1 = cv2.imread(img_name)
    im1 = cv2.imdecode(np.fromfile(img_name, dtype=np.uint8), -1)
    # 将图像转换为灰度图
    gray_img = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)
    # 将灰度图像转换为浮点数
    distImage = gray_img.astype(np.float64)
    # 使用Sobel算子计算边缘
    edgeSobel = cv2.Canny(gray_img, 50, 150)
    # 计算边缘的均值和标准差
    edgeMean = np.mean(edgeSobel)
    edgeStd = np.std(edgeSobel)
    # 计算局部方差
    localVariance = ndimage.variance(distImage)  # , mode='constant', cval=0.0)
    # 计算纹理的均值和标准差
    textureMean = np.mean(localVariance)
    textureStd = np.std(localVariance)
    # 计算质量分数
    ImageMean = np.mean(distImage)
    ImageStd = np.std(distImage)
    qnr = 20 * np.log10((edgeMean + textureMean + ImageMean) / (edgeStd + textureStd + ImageStd))
    print(qnr)
    return round(qnr, 1)


def background_task():
    file = open(folder_selected + os.sep + os.path.basename(folder_selected) + "quality.txt", "w", encoding="utf-8")
    i = 0
    progressbar['value'] = 0
    global my_files
    for imgFile in my_files:
        print(imgFile)
        qnr = main_quality_check(imgFile)  # folder_selected + os.sep +
        line_str = os.path.basename(imgFile) + "    " + str(qnr) + "\r\n"
        file.write(line_str)
        i = i + 1
        rate = i / len(my_files) * 100
        print(str(round(rate, 0)) + "%")
        # show_info.set(str(rate)+"%")
        progressbar['value'] = rate
    file.close()
    show_info.set("操作成功！")
    button.config(state="normal")


def choose_dir():
    global folder_selected
    folder_selected = filedialog.askdirectory()
    print(folder_selected)
    show_info.set(folder_selected)
    global my_files
    # my_files = os.listdir(folder_selected)
    pattern = os.path.join(folder_selected, "*.JPG")
    my_files1 = glob.glob(pattern)
    pattern = os.path.join(folder_selected, "*.jpeg")
    my_files2 = glob.glob(pattern)
    my_files = my_files1 + my_files2
    if len(my_files) == 0:
        show_info.set("目录中没有照片!")
        return
    button.config(state="disable")
    background_thread = threading.Thread(target=background_task)
    background_thread.daemon = True
    background_thread.start()


button = tk.Button(root, text="选择照片目录", command=choose_dir)
button.pack(side="top", pady=50)

show_info = tk.StringVar()
panel = tk.Label(root, text='图片目录:', textvariable=show_info)
panel.pack(side="top", padx="50", pady="50")

progressbar = ttk.Progressbar(root, orient='horizontal', length=300)
# progressbar.set(0)
progressbar.pack(side="top", pady=5, expand="yes")

root.mainloop()
